package com.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.common.R;
import com.erp.entity.Payable;
import com.erp.entity.Receivable;
import com.erp.service.ReceivableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/receivable")
@RequiresRoles(value = {"FinancialAdministrator","SupperAdministrator"},logical = Logical.OR)
public class ReceivableController {

    @Autowired
    private ReceivableService receivableService;

    /**
     * 保存应收账 （已测试）
     * @param receivable
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Receivable receivable){
        log.info("保存应收账");
        return receivableService.saveReceivableAndLedger(receivable);
    }

    /**
     * 根据id查询 （已测试）
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Receivable> findById(@PathVariable Long id){
        log.info("根据id查询应收账");
        return R.success(receivableService.getById(id));
    }

    @PutMapping
    public R<String> update(@RequestBody Receivable receivable){
        log.info("更新应付账信息");

        boolean b = receivableService.updateById(receivable);

        return R.success("更新成功");
    }

    /**
     * 根据id删除 （已测试）
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam Long id){
        log.info("根据id删除应收账");
        return receivableService.deleteByIdAndUpdateLedger(id);
    }

    /**
     * 查询全部数据 （已测试）
     * @return
     */
    @GetMapping("/list")
    public R<List<Receivable>> findAll(){
        log.info("查询应收账全部数据");
        return R.success(receivableService.list());
    }

    /**
     * 分页查询 （已测试）
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Receivable>> page(int page,int pageSize,String name){
        log.info("应收账分页查询");
        Page<Receivable> receivablePage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Receivable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Receivable::getCreateDateTime);
        if (name!=null){
            lambdaQueryWrapper.like(Receivable::getInformation,name);
        }
        receivableService.page(receivablePage,lambdaQueryWrapper);
        return R.success(receivablePage);
    }

}
